﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Security.Claims;

namespace Single.AppCore
{
    public static class GlobalApp
    {
        public static IConfiguration Configuration { get; set; }

        public static IHostEnvironment Environment { get; set; }

        public static IServiceCollection Services { get; set; }

        public static IServiceProvider RootServices { get; set; }

        public static IHttpContextAccessor HttpAccessor => GetService<IHttpContextAccessor>();

        public static ClaimsPrincipal User => HttpAccessor?.HttpContext?.User;

        public static string RootPath { get; set; }

        static GlobalApp()
        {
            RootPath = Directory.GetCurrentDirectory();
        }

        public static IHostApplicationBuilder Register(this IHostApplicationBuilder builder, params string[] jsonFiles)
        {
            foreach (var jsonFile in jsonFiles)
            {
                builder.Configuration.AddJsonFile(jsonFile);
            }

            Configuration = builder.Configuration;
            Environment = builder.Environment;
            Services = builder.Services;

            return builder;
        }

        public static IHostBuilder Register(this IHostBuilder builder, params string[] jsonFiles)
        {
            builder.ConfigureAppConfiguration((context, configurationBinder) =>
            {
                foreach (var jsonFile in jsonFiles)
                {
                    configurationBinder.AddJsonFile(jsonFile);
                }
            });

            builder.ConfigureServices((context, services) =>
            {
                Configuration = context.Configuration;
                Environment = context.HostingEnvironment;
                Services = services;
            });

            return builder;
        }

        public static IHost UseGlobalServices(this IHost host)
        {
            RootServices = host.Services; return host;
        }

        public static T GetOptions<T>(string key)
        {
            return Configuration.GetSection(key).Get<T>();
        }

        public static T GetService<T>()
        {
            return RootServices.GetService<T>();
        }

        public static string GetPhysicalPath(string path)
        {
            // 使用Path.Combine和环境无关的路径分隔符实现跨平台兼容
            string normalizedPath = path.TrimStart('/').Replace('/', Path.DirectorySeparatorChar);
            
            var ioPath = Path.Combine(RootPath, "wwwroot", normalizedPath);

            var dir = ioPath.Contains(".") ? Directory.GetParent(ioPath) : new DirectoryInfo(ioPath);

            if (!dir.Exists) { dir.Create(); }

            return ioPath;
        }
    }
}